package api

import (
	"api_gateway/basic/config"
	__ "api_gateway/basic/proto"
	"api_gateway/handler/request"
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"github.com/share309/gojwt"
	"net/http"
	"time"
)

func Register(c *gin.Context) {
	var req request.Register
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "验证失败",
			"data":    err.Error(),
		})
		return
	}
	register, err := config.UserClient.Register(c, &__.RegisterReq{
		Mobile:   req.Mobile,
		Password: req.Password,
		SmsCode:  req.SmsCode,
	})
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "注册失败",
			"data":    err.Error(),
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "注册成功",
		"data":    register,
	})

}

func Login(c *gin.Context) {
	var req request.Login
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "验证失败",
			"data":    err.Error(),
		})
		return
	}
	login, err := config.UserClient.Login(c, &__.LoginReq{
		Mobile:   req.Mobile,
		Password: req.Password,
		SmsCode:  req.SmsCode,
	})
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "登录失败",
			"data":    err.Error(),
		})
		return
	}
	token, err := gojwt.NewJWT(config.Jwt_KEY).CreateToken(gojwt.CustomClaims{
		ID: uint(login.UserId),
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: time.Now().Unix() * 3600 * 24 * 3,
		},
	})
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "获取token失败",
			"data":    err.Error(),
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "登录成功",
		"data":    token,
	})
}

func SendSms(c *gin.Context) {
	var req request.SendSms
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "验证失败",
			"data":    err.Error(),
		})
		return
	}
	sms, err := config.UserClient.SendSms(c, &__.SendSmsReq{Mobile: req.Mobile})
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "发送短信验证码失败",
			"data":    err.Error(),
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "发送成功",
		"data":    sms,
	})
}

func CheckUser(c *gin.Context) {
	var req request.CheckUser
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "验证失败",
			"data":    err.Error(),
		})
		return
	}
	user, err := config.UserClient.UpdateUser(c, &__.UpdateUserReq{
		UserId:   int64(req.Id),
		UserType: int64(req.User_type),
	})
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "切换失败",
			"data":    err.Error(),
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "切换成功",
		"data":    user,
	})
}
